<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>着色器实现像素动画-顶点着色器实现非固定帧动画</title>
    <style>
        canvas{
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <canvas width="512" height="512"></canvas>

    <script src="/common/lib/gl-renderer.js"></script>
    <script type="module">
        /**
         * gl-renderer用法
         * 1.创建renderer对象
         * 2.创建webgl程序
         * 3.设置uniform变量
         * 4.设置缓冲区数据
         * 5.渲染
         * 
         * */ 

        //  1.
         const canvas = document.querySelector("canvas");
         const renderer = new GlRenderer(canvas);

        (async function(){
            // 2.
            const vertex = `
                attribute vec2 a_vertexPosition;
                attribute vec2 uv;
                varying vec2 vUv;

                uniform float uTime;
                
                void main() {
                    gl_PointSize = 1.0;
                    vUv = uv;
                    float c = cos(uTime);
                    float s = sin(uTime);
                    mat3 rotateMatirx = mat3(
                        c, s, 0.0,
                        -s, c, 0.0, 
                        0.0, 0.0, 1.0
                    );
                    vec3 pos = rotateMatirx * vec3(a_vertexPosition, 1.0);
                    gl_Position = vec4(pos, 1.0);
                }
            `;
            const fragment = `
                #ifdef GL_ES
                    precision mediump float;
                #endif
    
                varying vec2 vUv;
                
                void main() {
                    vec2 st = vUv;
                    
                    vec4 color = vec4(1.0, 0.0, 0.0, 1.0);
                    gl_FragColor = color;
                }
            `;
    
            const program = renderer.compileSync(fragment,vertex);
            renderer.useProgram(program);
    
            // 3.
            renderer.uniforms.uTime = 0;
    
            // 4.
            const x = 0.5;
            const y = 0.5;
            renderer.setMeshData([{
                positions:[
                    [-x, -y],
                    [-x, y],
                    [x, y],
                    [x, -y],
                ],
                attributes:{
                    uv:[
                        [0, 0],
                        [0, 1],
                        [1, 1],
                        [1, 0],
                    ]
                },
                cells: [[0, 1, 2], [2, 0, 3]],
            }]);
    
            // 5.
            renderer.render();

            function update(t){
                renderer.uniforms.uTime = t * 0.003;
                requestAnimationFrame(update);
            }
            update(0)
        })();

    </script>
</body>
</html>